package com.iussoft.receiveData.schedul;

import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.tools.UUIDUtil;
import com.iussoft.receiveData.redis.EsManager;
import com.iussoft.tools.AddressUtils;
import com.iussoft.tools.SpringContextLoader;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 日志写入线程
 * @author: Hou Dayu
 * @date: Created in 2020/9/7
 */
public class LogWritRunable implements Runnable {

    private String message;
    private String levelStr;
    private String indexName;

    public LogWritRunable(String message,String levelStr,String indexName){
        this.message = message;
        this.levelStr = levelStr;
        this.indexName = StrUtil.doNull(indexName,"data-warn")+"-"+ DateUtils.Now.fmt_yyyyMM();
    }

    @Override
    public void run() {
        Map<String,String> object = new HashMap();
        try {
            object.put("ipAddress", AddressUtils.getHostIp());
            String str[] = message.split(";");
            for(int i= 0;i<str.length;i++){
                String vals[] = str[i].split(" = ");
                if(vals.length>1 && StrUtil.isNotNull(vals[1])) {
                    object.put(vals[0].trim(), vals[1]);
                }
            }
            //object.put("message",message.replaceAll("\n","").replaceAll("\r","").replaceAll(";","；"));
            if(!object.containsKey("level")) {
                object.put("level", levelStr);
            }
            EsManager esManager = (EsManager) SpringContextLoader.getBean("esManager");
            esManager.saveInfoForLogs(indexName,"data-warn", UUIDUtil.getPrimaryKey(), object);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
